package com.diao.flink.state;

import com.google.common.collect.Lists;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.LocalStreamEnvironment;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;


import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.UUID;

/**
 * @author: chenzhidiao
 * @date: 2021/1/19 16:50
 * @description: 测试 KeyedState 的 MapState
 * MapState<K, V> ：这个状态为每一个 key 保存一个 Map 集合
 *      put() 将对应的 key 的键值对放到状态中
 *      values() 拿到 MapState 中所有的 value
 *      clear() 清除状态
 *
 * @version: 1.0
 */
public class KeyedMapStateDemo {
    public static void main(String[] args) throws Exception {
        LocalStreamEnvironment env = StreamExecutionEnvironment.createLocalEnvironment(new Configuration());

        DataStreamSource<Tuple2<Long,Long>> dataStream = env.fromElements(Tuple2.of(1L, 3L), Tuple2.of(1L, 5L), Tuple2.of(1L, 7L), Tuple2.of(2L, 4L), Tuple2.of(2L, 2L), Tuple2.of(2L, 5L));

        dataStream.keyBy(0).flatMap(new CountWindowAverageWithMapState()).print();

        env.execute("TestStatefulApi");


    }
}

class CountWindowAverageWithMapState extends RichFlatMapFunction<Tuple2<Long,Long>,Tuple2<Long,Double>>{

    // managed keyed state
    // 1. MapState ：key 是一个唯一的值，value 是接收到的相同的 key 对应的 value 的值
    private MapState<String,Long> mapState;

    @Override
    public void open(Configuration parameters){
        MapStateDescriptor<String, Long> mapStateDescriptor = new MapStateDescriptor<>("mapState", String.class, Long.class);

        mapState = getRuntimeContext().getMapState(mapStateDescriptor);
    }

    @Override
    public void flatMap(Tuple2<Long,Long> value, Collector<Tuple2<Long,Double>> out) throws Exception {

        mapState.put(UUID.randomUUID().toString(),value.f1);

        ArrayList<Long> allElements = Lists.newArrayList(mapState.values());

        if (allElements.size()>=3){
            long count = 0;
            long sum = 0;
            for (Long allElement : allElements) {
                count++;
                sum += allElement;
            }
            double avg = (double) sum/count;

            out.collect(Tuple2.of(value.f0,avg));

            mapState.clear();
        }

    }
}
